package taskman.ui;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

import taskman.Task;
import taskman.xml.XmlHelper;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.List;

public class TreeViewWindow extends JFrame
{
	public TreeViewWindow() 
	{	
		List<Task> tasks = XmlHelper.loadAllTasks();
		JTree tree = new JTree(buildTree(tasks));
		getContentPane().add(tree, BorderLayout.CENTER);
	}

	
	private DefaultMutableTreeNode buildTree(List<Task> tasks)
	{
		Hashtable<String, DefaultMutableTreeNode> rootLevelNodesMap = new Hashtable<String, DefaultMutableTreeNode>();
		
		//1. We scan the task for all root level tasks.
		// Root level tasks are those that DO NOT have a parent task, i.e: parentTaskID=null
		for (Task task : tasks)
		{
			if(task.getParentTaskId()==null)
			{
				rootLevelNodesMap.put(task.getId(),new DefaultMutableTreeNode(task.getTitle()+" (id="+ task.getId()+")"));
			}
		}
		
		//2. we do a second pass and figure out which substask fall under the
		// root level tasks.
		for (Task task : tasks)
		{
			if(task.getParentTaskId()!=null)
			{
				String parentTaskId = task.getParentTaskId();
				DefaultMutableTreeNode parentTaskNode = rootLevelNodesMap.get(parentTaskId);
				parentTaskNode.add(new DefaultMutableTreeNode(task.getTitle()+" (id="+ task.getId()+")"));
			}
		}
		
		//3. finally we create the root node and add all rootlevel nodes.
		DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Tasks");
		Collection<DefaultMutableTreeNode> rootlevelNodes = rootLevelNodesMap.values();
		for (DefaultMutableTreeNode rootLevelNode : rootlevelNodes)
		{
			rootNode.add(rootLevelNode);
		}
		
		return rootNode;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					TreeViewWindow frame = new TreeViewWindow();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

}
